const { status } = require("init")
    // const db = require('db')
const db = require('../db/index')



exports.getBook = (req, res) => {
    // res.send('我是要处理的函数')
    const sql = 'select * from book'
    db.query(sql, (err, results) => {
        if (results.length > 0) {
            return res.send({
                status: 200,
                message: '已经查到了',
                data: results
            })
        }
    })
}


exports.selectBook = (req, res) => {
    const userinfo = req.query
    const sql = 'select * from book where bookname=?'
        // res.send(userinfo.bookname)
        // console.log(userinfo.bookname)
        // console.log(11);
        // res.send(userinfo.bookname)
    db.query(sql, userinfo.bookname, (err, results) => {
        if (err) {
            return res.send({
                status: 401,
                message: '执行sql失败',
                data: results
            })
        } else {
            return res.send({
                status: 200,
                message: '查询成功',
                data: results
            })
        }
    })
}

exports.addBook = (req, res) => {
    const userinfo = req.body
    const sql = 'insert into book set ?'
    db.query(sql, { bookname: userinfo.bookname, author: userinfo.author, publisher: userinfo.publisher }, (err, results) => {
        if (err) {
            return res.send({
                status: 404,
                message: 'sql执行失败',
                data: results
            })
        } else {
            return res.send({
                status: 200,
                message: '新增图书成功',
                data: results
            })
        }
    })
}

exports.delBook = (req, res) => {
    const userinfo = req.body
    const sql = 'delete from book where id=?'
        // console.log(userinfo.id);
    db.query(sql, userinfo.id, (err, results) => {
        if (err) {
            return res.send({
                status: 401,
                message: '执行sql失败',
                data: results
            })
        } else {
            return res.send({
                status: 200,
                message: '删除图书成功',
                data: results
            })
        }
    })

}

exports.selectAllBooks = (req, res) => {
    const sql = 'SELECT COUNT(id) as l from book'
    db.query(sql, (err, results) => {
        if (results.length > 0) {
            return res.send({
                status: 200,
                message: '已经查到了书的数目',
                data: results
            })
        }
    })
}